package org.changs.record.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.os.Bundle;

import org.changs.aplug.base.BaseActivity;
import org.changs.media.MediaFile;
import org.changs.media.MediaManager;
import org.changs.record.R;
import org.changs.record.databinding.ActivityMainBinding;
import org.changs.record.picture.PictureFragment;
import org.changs.record.video.VideoFragment;
import org.changs.record.video.VideoPlayAct;
import org.changs.s3.common.RemoteManager;

import javax.inject.Inject;

import dagger.Lazy;

public class MainActivity extends BaseActivity implements MainContract.V {

    @Inject
    MediaManager mMediaManager;

    @Inject
    RemoteManager mRemoteManager;

    @Inject
    Lazy<PictureFragment> mPictureFragment;

    @Inject
    Lazy<VideoFragment> mVideoFragment;

    @Inject
    MainPresenter mMainPresenter;

    private ActivityMainBinding mBinding;


    @Override
    public void setup(Bundle savedInstanceState) {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(VideoPlayAct.ACTION_DELETE_MEDIA_FILE);
        registerReceiver(mReceiver, intentFilter);

        mMainPresenter.attachView(this);
        mBinding.rg.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rbtn_video:
                    mVideoFragment.get().show();
                    mPictureFragment.get().hide();
                    break;
                case R.id.rbtn_picture:
                    mVideoFragment.get().hide();
                    mPictureFragment.get().show();
                    break;
            }
        });
        mBinding.rbtnVideo.setChecked(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        mMainPresenter.detachView();
    }

    @Override
    public void afterLoadMedia() {

    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (VideoPlayAct.ACTION_DELETE_MEDIA_FILE.equals(intent.getAction())) {
                MediaFile mediaFile = intent.getParcelableExtra(VideoPlayAct.TAG_MEDIA_FILE);
                if (mediaFile != null) {
                    mMediaManager.delete(mediaFile);
                }
            }
        }
    };
}
